package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;


    @Override
    public AddressBook getDefault() {
        return addressBookMapper.selectOne(new QueryWrapper<AddressBook>()
                        .eq("user_id", BaseContext.getCurrentId())
                        .eq("is_default", 1)
        );
    }

    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        return addressBookMapper.selectList(new QueryWrapper<AddressBook>()
                .eq("user_id", BaseContext.getCurrentId())
        );
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.selectById(id);
    }

    @Override
    public void updateDefault(Long id) {
        addressBookMapper.update(new UpdateWrapper<AddressBook>()
                .eq("user_id", BaseContext.getCurrentId())
                .eq("is_default", 1)
                .set("is_default", 0))
        ;
        addressBookMapper.updateById(AddressBook.builder().id(id).isDefault(1).build());
    }
}
